#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
//#include <stdlib.h>

struct Wifi_ssid {
    std::string ssid;
    std::string encrypt;
    int level;
};

using namespace std;

vector<Wifi_ssid> ssid_list;
Wifi_ssid ssid_cur;
string::size_type pos;

bool wifi_sort(const Wifi_ssid &a, const Wifi_ssid &b)
{
    return a.level > b.level;
}

int main() {
    system("iw dev wlan0 scan > /tmp/iw_scan.log");
    ifstream infile("/tmp/iw_scan.log");
    string s;
    string str_skip;

    while (getline(infile, s)) {
        pos = s.find("BSS");
        if (pos == 0) {
            if (ssid_cur.ssid.length() != 0)
                ssid_list.push_back(ssid_cur);
            //cout << s << endl;
            ssid_cur.ssid = "";
            ssid_cur.encrypt = "none";
        }

        pos = s.find("\tsignal:");
        if (pos == 0) {
            int dbm;
            stringstream ss(s);
            ss >> str_skip;
            ss >> dbm;
            //cout << s << " dbm=" << dbm << endl;

            if (dbm >= -50)
                ssid_cur.level = 100;
            else if (dbm >= -80)
                ssid_cur.level = 24 +((dbm + 80) * 26) / 10;
            else if (dbm >= -90)
                ssid_cur.level = (dbm + 90) * 26 / 10;
            else
                ssid_cur.level = 0;
        }

        pos = s.find("\tSSID:");
        if (pos == 0)
            ssid_cur.ssid = s.erase(0, 7);  //TODO: check special char

        pos = s.find("\tRSN:") && s.find("\tWPA:");
        if (pos == 0)
            ssid_cur.encrypt = "wpa";

        pos = s.find("\tWEP:");
        if (pos == 0)
            ssid_cur.encrypt = "wep";
    }
    if (ssid_cur.ssid.length() != 0)
        ssid_list.push_back(ssid_cur);

    sort(ssid_list.begin(), ssid_list.end(), wifi_sort);

    bool virgin = true;
    cout << "[";
    for (vector<Wifi_ssid>::size_type i = 0; i != ssid_list.size(); ++i) {
        if (virgin)
            virgin = false;
        else
            cout << ", ";

        cout << "{\"ssid\": \"" << ssid_list[i].ssid
                << "\", \"encrypt\": \"" << ssid_list[i].encrypt
                << "\", \"level\": \"" << ssid_list[i].level << "\"}";
    }
    cout << "]" << endl;

    return 0;
}
